package com.itheima.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckItemDao;
import com.itheima.entity.CheckItemDeleteFailException;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = CheckItemService.class)
@Transactional
public class CheckItemServiceImpl implements CheckItemService{
    @Autowired
    private CheckItemDao checkItemDao;
    @Override
    public void add(CheckItem checkItem) {
        checkItemDao.save(checkItem);
    }

    @Override
    public PageResult find(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页查询
        PageHelper.startPage(currentPage,pageSize);
        //调用方法查询
        Page<CheckItem> page = checkItemDao.selectByCondition(queryString);
        //得到总条数
        long total = page.getTotal();
        //得到数据
        List<CheckItem> result = page.getResult();
        return new PageResult(total,result);
    }

    @Override
    public void delete(Integer id) throws CheckItemDeleteFailException {
        //得到关联数
        long count = checkItemDao.findCountById(id);
        //如果大于0,则表示有关联,不能删除,抛异常
        System.out.println(count);
        if (count > 0 ){
            //抛出自定义异常
            throw new CheckItemDeleteFailException();
        }
        checkItemDao.deleteById(id);
    }

    @Override
    public void update(CheckItem checkItem) {
        checkItemDao.update(checkItem);
    }

    @Override
    public List<CheckItem> findAll() {
        return checkItemDao.findAll();
    }
}
